import { useState, useEffect } from "react";
import { message, Switch, Upload } from "antd";
import type { GetProp, UploadFile, UploadProps } from "antd";
import ImgCrop from "antd-img-crop";
import UploadImg from "../../../../components/UploadImg";
import { RightOutlined, PlusOutlined } from "@ant-design/icons";
import { request } from "../../../../common/request";
import { urls } from "../../../../common/urls";
import { useNavigate } from "react-router-dom";
import { sendMessage } from '../../../../util/message';
import "./index.less";

type FileType = Parameters<GetProp<UploadProps, "beforeUpload">>[0];

function GroupItem(props: any) {
  const { id } = props;
  const [info, setInfo]: any = useState({});
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [blocked, setBlocked] = useState(false);
  const [auth, setAuth] = useState(false);
  const navigate = useNavigate()

  const onChange: UploadProps["onChange"] = ({ fileList: newFileList }) => {
    setFileList(newFileList);
  };

  const onPreview = async (file: UploadFile) => {
    let src = file.url as string;
    if (!src) {
      src = await new Promise((resolve) => {
        const reader = new FileReader();
        reader.readAsDataURL(file.originFileObj as FileType);
        reader.onload = () => resolve(reader.result as string);
      });
    }
    const image = new Image();
    image.src = src;
    const imgWindow = window.open(src);
    imgWindow?.document.write(image.outerHTML);
  };

  const getInfo = (id: string) => {
    request({
      method: "post",
      data: {
        method: urls.getGroupDetail,
        group_id: id
      },
    }).then((res: any) => {
      console.log('group', res.data);
      const info = res.data;
      const { is_all_blocked, status_auth } = info;
      const fileList = info.members.map((x: any) => {
        return {
          uid: x.uid,
          name: x.username,
          status: "done",
          url: x.avatar,
        };
      })
      setInfo(res.data);
      setBlocked(is_all_blocked);
      setAuth(status_auth);
      setFileList(fileList);
    });
  }

  const onHideChange = (checked: boolean) => {
    request({
      method: "post",
      data: {
        method: urls.updateDisableTalk,
        group_id: id
      },
    }).then((res: any) => {
      setBlocked(res.data.is_all_blocked);
    });
  };

  const onGroupChange = (checked: boolean) => {
    request({
      method: "post",
      data: {
        method: urls.updateAddGroupStatus,
        group_id: id
      },
    }).then((res: any) => {
      setAuth(res.data.status_auth);
    });
  };

  const handleAvatar = (logo: string) => {
    request({
      method: "post",
      data: {
        method: urls.updateGroupLogo,
        group_id: id,
        logo
      },
    }).then((res: any) => {
      setAuth(res.data.status_auth);
    });
  };

  const handleExitGroup = () => {
    message.warning('接口缺失');
  };

  const handleSend = () => {
    console.log(info);
    sendMessage('', info.group_id.toString(), 'groupChat').then((res => {
      if (res.id) {
        navigate('/chat');
      }
    }))
  };

  useEffect(() => {
    console.log('id', id);
    getInfo(id);
  }, [id])


  return (
    <>
      <div className="user-content group-content">
        <div className="flex-base group-content-top">
          <ImgCrop rotationSlider>
            <Upload
              action="https://run.mocky.io/v3/435e224c-44fb-4773-9faf-380c5e6a2188"
              listType="picture-card"
              fileList={fileList}
              onChange={onChange}
              onPreview={onPreview}
            >
              <PlusOutlined />
            </Upload>
          </ImgCrop>
          <div className="group-img-all">
            <p>查看</p>
            <p>全部成员</p>
          </div>
        </div>
        <div className="user-link-group">
          <div className="link-item">
            <div>群头像</div>
            <div className="flex-base">
              <UploadImg getAvatar={handleAvatar} groupImg={info.logo} className="group-img" />
              <RightOutlined />
            </div>
          </div>
          <div className="link-item">
            <div>群名称</div>
            <div>
              {info.name}
            </div>
          </div>
          <div className="link-item">
            <div>群号码</div>
            <div>
              {info.team_id}
            </div>
          </div>
          <div className="link-item">
            <div>群二维码</div>
            <div className="flex-center">
              <img
                src={info.code}
                className="qr-img"
                alt=""
              />
              <RightOutlined />
            </div>
          </div>
          <div className="group-notice">
            <p>群公告</p>
            <div
              className="group-notice-main flex-base"
              style={{ cursor: "pointer" }}
            >
              <p>{info.reject_msg}</p>
              <RightOutlined />
            </div>
          </div>
          {
            info.is_owner
              ? <>
                <div className="link-item">
                  <div>管理员设置</div>
                  <div>
                    <RightOutlined />
                  </div>
                </div>
                <div className="link-item">
                  <div>群主转让</div>
                  <div>
                    <RightOutlined />
                  </div>
                </div>
                <div className="link-item">
                  <div>群成员禁言</div>
                  <div>
                    <RightOutlined />
                  </div>
                </div>
                <div className="link-item">
                  <div>全体禁言</div>
                  <div>
                    <Switch checked={blocked} onChange={onHideChange} />
                  </div>
                </div>
                <div className="link-item">
                  <div>加群验证</div>
                  <div>
                    <Switch checked={auth} onChange={onGroupChange} />
                  </div>
                </div>
              </>
              : null
          }
        </div>
        <div className="user-btn-group">
          <div className="btn-default" onClick={handleExitGroup}>{info.is_owner ? '解散群聊' : '退出群聊'}</div>
          <div className="btn-default active-btn" onClick={handleSend}>发消息</div>
        </div>
      </div>
    </>
  );
}
export default GroupItem;
